package com.chushouya.order.service.api.impl;

import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Check;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Strings;
import com.chushouya.order.constants.ClerkOrderActionEnum;
import com.chushouya.order.constants.OrderPayStatusEnum;
import com.chushouya.order.constants.OrderStatusEnum;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dto.api.clerk.action.ClerkOrderAction;
import com.chushouya.order.service.api.ClerkOrderActionCtrlApiService;
import com.chushouya.order.util.ClerkOrderActionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.chushouya.order.dao.entity.OrderEntity;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class ClerkOrderActionCtrlApiServiceImpl implements ClerkOrderActionCtrlApiService {

    @Resource
    private OrderRepository orderRepository;

//    @Resource
//    private ClerkOrderBackoutApiService clerkOrderBackoutApiService;
//
//    @Resource
//    private ClerkOrderSelfSaleApiService clerkOrderSelfSaleApiService;

    private OrderEntity getOrder(Long orderId, Long clerkId) {
        final OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        Check.notNull(orderEntity, "订单不存在");
        Check.notFalse(Objects.equals(clerkId, orderEntity.getClerkId()), Strings.format("非法操作[业务员{}不可操作当前订单]", clerkId));
        return orderEntity;
    }


    @Override
    public List<ClerkOrderAction> orderActions(Long orderId, Long clerkId) {
        return this.getActionList(this.getOrder(orderId, clerkId));
    }

    @Override
    public void actionExecuteCheck(ClerkOrderActionEnum orderAction, OrderEntity orderEntity) {
        // 订单xxx，不能执行xxx
        OrderStatusEnum orderStatus = OrderStatusEnum.get(orderEntity.getOrderStatus());
        Boolean allowExecute = Objects.nonNull(this.getActionList(orderEntity).stream().filter(f -> Objects.equals(f.getActionCode(), orderAction.getActionCode())).findFirst().orElse(null));
        log.info("orderAction:{},orderStatus:{},allowExecute:{}",orderAction,orderStatus,allowExecute);
        if (!allowExecute && orderAction.moreCondition()) {
            throw Ex.business("当前订单不可操作[{}]", orderAction.named());
        }
        Check.notFalse(allowExecute, "[{}]状态订单不可操作[{}]", orderStatus.named(), orderAction.named());
    }

    private List<ClerkOrderAction> getActionList(OrderEntity orderEntity) {
        final List<ClerkOrderAction> actions = ClerkOrderActionUtil.clerkOrderActions(orderEntity.getOrderStatus());
        // 订单待确认/待上门时，子业务操作按钮控制
        if (Lists.asList(OrderStatusEnum.WAIT_CONFIRM.value(), OrderStatusEnum.WAIT_VISIT.value(),OrderStatusEnum.WAIT_BARGAIN.value(),OrderStatusEnum.WAIT_PAY.value()).contains(orderEntity.getOrderStatus())) {
            this.orderBackoutActionCtrl(actions, orderEntity);   // 业务员撤单按钮
        }

        //完成订单按钮
        if (Lists.asList(OrderStatusEnum.WAIT_PAY.value()).contains(orderEntity.getOrderStatus())){
            this.orderCompleteActionCtrl(actions, orderEntity);   // 业务员订单按钮
        }

        // 订单完成状态下，子业务操作按钮控制
        if (Objects.equals(OrderStatusEnum.COMPLETE.value(), orderEntity.getOrderStatus())) {
            this.requestSelfSaleActionCtrl(actions, orderEntity); // 申请自卖按钮
            this.backoutSelfSaleActionCtrl(actions, orderEntity);  // 撤销自卖按钮
            this.deliveryActionCtrl(actions, orderEntity);        // 订单发货按钮
        }
        //重置按钮
        if (Lists.asList(OrderStatusEnum.CLOSED.value(), OrderStatusEnum.CANCELLED.value(), OrderStatusEnum.CLERK_CANCEL.value(), OrderStatusEnum.BACKOUT_CLOSED.value(),OrderStatusEnum.TIMEOUT.value()).contains(orderEntity.getOrderStatus())) {
            this.resetOrderStatusActionCtrl(actions, orderEntity);
        }

        return actions;
    }

    /**
     * 待确认/待上门,撤单按钮
     */
    private void orderBackoutActionCtrl(List<ClerkOrderAction> actions, OrderEntity orderEntity) {
        final ClerkOrderActionEnum action = ClerkOrderActionEnum.CLERK_BACKOUT;
        // 查询是否有撤单申请记录
//        Boolean hasOrderBackoutRequest = clerkOrderBackoutApiService.hasOrderBackoutRequest(orderEntity.getOrderId());
//        if (!hasOrderBackoutRequest) {
//            actions.add(new ClerkOrderAction(action.getActionCode(), action.getActionName(), action.getActionText(), action.getActionType()));
//        }
    }

    /**
     * 已收成订单-发货按钮
     */
    private void deliveryActionCtrl(List<ClerkOrderAction> actions, OrderEntity orderEntity) {
        final ClerkOrderActionEnum action = ClerkOrderActionEnum.DELIVERY;
//        Boolean hasSelfSaleRequest = clerkOrderSelfSaleApiService.hasSelfSaleRequest(orderEntity.getOrderId());
//        if (Objects.equals(orderEntity.getLogisticsStatus(), LogisticsStatusEnum.WAIT_DELIVERY.value()) && !hasSelfSaleRequest) {
//            actions.add(new ClerkOrderAction(action.getActionCode(), action.getActionName(), action.getActionText(), action.getActionType()));
//        }
    }

    /**
     * 已收成订单-申请自卖按钮
     */
    private void requestSelfSaleActionCtrl(List<ClerkOrderAction> actions, OrderEntity orderEntity) {
        final ClerkOrderActionEnum action = ClerkOrderActionEnum.REQUEST_SELF_SALE;
        // 查询是否有自卖记录
//        Boolean hasSelfSaleRequest = clerkOrderSelfSaleApiService.hasSelfSaleRequest(orderEntity.getOrderId());
//        if (!hasSelfSaleRequest && Objects.equals(orderEntity.getLogisticsStatus(), LogisticsStatusEnum.WAIT_DELIVERY.value())) {
//            actions.add(new ClerkOrderAction(action.getActionCode(), action.getActionName(), action.getActionText(), action.getActionType()));
//        }
    }

    /**
     * 已收成订单-撤销自卖按钮
     */
    private void backoutSelfSaleActionCtrl(List<ClerkOrderAction> actions, OrderEntity orderEntity) {
        final ClerkOrderActionEnum action = ClerkOrderActionEnum.BACKOUT_SELF_SALE;
//        Boolean hasSelfSaleRequest = clerkOrderSelfSaleApiService.hasSelfSaleRequest(orderEntity.getOrderId());
//        if (hasSelfSaleRequest && Objects.equals(orderEntity.getLogisticsStatus(), LogisticsStatusEnum.NONE.value())) {
//            actions.add(new ClerkOrderAction(action.getActionCode(), action.getActionName(), action.getActionText(), action.getActionType()));
//        }
    }

    /**
     * 重置订单
     */
    private void resetOrderStatusActionCtrl(List<ClerkOrderAction> actions, OrderEntity orderEntity) {
        final BigDecimal prepaidPrice = orderEntity.getPrepaidPrice();
        final Date createTime = orderEntity.getCreateTime();
        if (prepaidPrice.compareTo(BigDecimal.ZERO) > 0) {
            return;
        }
        if (createTime.before(Dates.addMonths(Dates.getTimeNow(), -1))) {
            return;
        }
        final ClerkOrderActionEnum action = ClerkOrderActionEnum.RESET_ORDER_STATUS;
        actions.add(new ClerkOrderAction(action.getActionCode(), action.getActionName(), action.getActionText(), action.getActionType()));
    }

    /**
     * 完成订单按钮
     */
    private void orderCompleteActionCtrl(List<ClerkOrderAction> actions, OrderEntity orderEntity) {
        final Integer payStatus = orderEntity.getPayStatus();
        final String platform = orderEntity.getPlatform();
        final ClerkOrderActionEnum action;
        if (Objects.equals(payStatus, OrderPayStatusEnum.DEDUCTION.value())) {
            action = ClerkOrderActionEnum.NO_CONFIRM_COMPLETE;
        }else {
            action = ClerkOrderActionEnum.COMPLETE;
        }

        actions.add(new ClerkOrderAction(action.getActionCode(), action.getActionName(), action.getActionText(), action.getActionType()));
    }
}
